import React, { useContext, useState, useEffect, useMemo, useReducer } from 'react';

const fetchData = () => {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve(1);
        });
    });
};

const MyContext = React.createContext(null);
const MyContext2 = React.createContext(null);
const initState = { count: 0, step: 0, number: 0 };
const reducer = (state, action) => {
    switch (action.type) {
        case 'stepInc': return Object.assign({}, state, { step: state.step + 1 });
        case 'numberInc': return Object.assign({}, state, { number: state.number + 1 });
        case 'count': return Object.assign({}, state, { count: state.step + state.number });
        default: return state;
    }
};
// useRef保存的是同一个引用，createRef是最新的引用
export default () => {
    // 高阶组件
    // const checkDataIfExit = arr => target => arr.includes(target);
    // useEffect(() => {
    //     const listA = [1, 2, 3, 4, 5];
    //     const listB = [2, 3, 4];
    //     const IfDataExit = checkDataIfExit(listB);
    //     let b = listA.filter(item => IfDataExit(item));
    //     console.log(b);
    // });
    const [state, dispatch] = useReducer(reducer, initState);
    const [vv, setstate] = useState('test');
    const ctx = React.useMemo(() => ({
        state,
        dispatch
    }), [state]);
    return (
        <MyContext.Provider value={ctx}>
            <MyContext2.Provider value={{ vv }}>
                <Child />
            </MyContext2.Provider>
        </MyContext.Provider>
    );
};

const Child = (props = {}) => {
    const { dispatch, state } = useContext(MyContext);
    const { vv } = useContext(MyContext2);
    const { step, number, count } = state;
    useEffect(() => {
        console.log(vv, 'vvvvvvvvv');
    }, []);
    return useMemo(() => (
        <div>
            {console.log('[Child] RE-RENDER')}
            <p>step is : {step}</p>
            <p>number is : {number}</p>
            <p>count is : {count}</p>
            <hr />
            <div>
                <button onClick={() => { dispatch({ type: 'stepInc' }); }}>step ++</button>
                <button onClick={() => { dispatch({ type: 'numberInc' }); }}>number ++</button>
                <button onClick={() => { dispatch({ type: 'count' }); }}>number + step</button>
            </div>
        </div>
    ), [step, number, count, dispatch]);
};